package com.njit.campuslifeboot.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.njit.campuslifeboot.annotation.AuthAnnotation;
import com.njit.campuslifeboot.entity.dto.LifeInfoDTO;
import com.njit.campuslifeboot.entity.dto.ListDTO;
import com.njit.campuslifeboot.entity.dto.ListResult;
import com.njit.campuslifeboot.entity.po.LifeInfo;
import com.njit.campuslifeboot.entity.po.User;
import com.njit.campuslifeboot.service.ILifeInfoService;
import com.njit.campuslifeboot.service.IUserService;
import com.njit.campuslifeboot.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

import static com.njit.campuslifeboot.util.JsonResult.success;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Axin
 * @since 2022-11-07
 */
@RestController
@RequestMapping("/life-info")
public class LifeInfoController {
    @Autowired
    private ILifeInfoService lifeInfoService;
    @Autowired
    private IUserService userService;

    @PostMapping("/addLifeInfo")
    @AuthAnnotation
    public JsonResult<Void> addLifeInfo(@RequestBody LifeInfoDTO lifeInfoDTO, HttpServletRequest request) {
        String username = request.getHeader("auth");
        User user = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        boolean flag = lifeInfoService.addLifeInfo(lifeInfoDTO, user.getId(), lifeInfoDTO.getPower());
        return flag ? success() : JsonResult.fail("addLifeInfoPublic error");
    }

    /**
     * 瀑布流加载,查看公共信息和自己信息
     */
    @PostMapping("/listLifeInfo")
//    @AuthAnnotation
    public JsonResult<ListResult<ListDTO>> getLifeList(@RequestBody LifeInfoDTO lifeInfoDTO, HttpServletRequest request) {
        String username = request.getHeader("auth");
        User user = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        if (lifeInfoDTO.getLastTime() == null) {
            lifeInfoDTO.setLastTime(LocalDateTime.now());
        }
        List<ListDTO> list;
        if (lifeInfoDTO.getUserId() != null && lifeInfoDTO.getUserId() != 0) {
            list = lifeInfoService.getSomeOneLifeList(lifeInfoDTO);
        } else {
            if (lifeInfoDTO.getPower() == 1) {
                list = lifeInfoService.getLifeList(lifeInfoDTO, user.getId());
            } else {
                list = lifeInfoService.getLifeListPrivate(lifeInfoDTO, user.getId());
            }
        }
        if (list == null || list.size() == 0) {
            return JsonResult.warn("No lifeList");
        }
        for (int i = 0; i < list.size(); i++) {
            LifeInfo byId = lifeInfoService.getById(list.get(i).getId());
            String likeList = byId.getLikeList();
            List<String> array = JSON.parseArray(likeList, String.class);
            if (array != null) {
                list.get(i).setLikeNum(array.size());
            }
        }
        ListResult<ListDTO> result = new ListResult<>();
        result.setData(list);
        result.setLastTime(list.get(list.size() - 1).getCreateTime());
        return JsonResult.success(result);
    }

    @GetMapping("/friendLifeInfo")
    public JsonResult<ListResult<ListDTO>> getLifeList(HttpServletRequest request) {
        String username = request.getHeader("auth");
        User user = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        String followIds = user.getFollowIds();
        if (followIds == null || Objects.equals(followIds, "")) {
            return JsonResult.success();
        }
        List<String> ids = JSON.parseArray(followIds, String.class);
        List<ListDTO> list = lifeInfoService.getFriendsLife(ids);
        if (list == null || list.size() == 0) {
            return JsonResult.warn("No lifeList");
        }
        for (int i = 0; i < list.size(); i++) {
            LifeInfo byId = lifeInfoService.getById(list.get(i).getId());
            String likeList = byId.getLikeList();
            List<String> array = JSON.parseArray(likeList, String.class);
            if (array != null) {
                list.get(i).setLikeNum(array.size());
            }
        }
        ListResult<ListDTO> result = new ListResult<>();
        result.setData(list);
        result.setLastTime(list.get(list.size() - 1).getCreateTime());
        return JsonResult.success(result);
    }

    @GetMapping("/deleteLifeInfo")
//    @AuthAnnotation
    public JsonResult<Void> deleteLifeInfo(@RequestParam("id") Integer id, HttpServletRequest request) {
        String username = request.getHeader("auth");
        User user = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        LifeInfo byId = lifeInfoService.getById(id);
        if (!Objects.equals(byId.getUserId(), user.getId())) {
            return JsonResult.fail("Can't delete others message");
        }
        QueryWrapper<LifeInfo> queryWrapper = new QueryWrapper<>();
        boolean remove = lifeInfoService.remove(queryWrapper.eq("ID", id).eq("USER_ID", user.getId()));
        return remove ? JsonResult.success() : JsonResult.fail("DeleteLifeInfo error");
    }

    @GetMapping("/like")
    @AuthAnnotation
    public JsonResult<Void> likeLifeInfo(@RequestParam("infoId") Integer infoId, HttpServletRequest request) {
        String username = request.getHeader("auth");
        User user = userService.getOne(new QueryWrapper<User>().eq("USERNAME", username));
        LifeInfo info = lifeInfoService.getOne(new QueryWrapper<LifeInfo>().eq("ID", infoId));
        String likeList = info.getLikeList();
        List<String> list;
        if (likeList == null || likeList.equals("")) {
            list = new ArrayList<>();
            list.add(user.getId().toString());
            String jsonString = JSON.toJSONString(list);
            boolean update = lifeInfoService.update(new UpdateWrapper<LifeInfo>().eq("ID", infoId).set("LIKE_LIST", jsonString));
            return update ? JsonResult.success() : JsonResult.fail("likeLifeInfo empty error");
        }
        list = JSON.parseArray(likeList, String.class);
        boolean isLiked = false;
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String s = iterator.next();
            if (s.equals(user.getId().toString())) {
                iterator.remove();
                isLiked = true;
                break;
            }
        }
        if (!isLiked) {
            list.add(user.getId().toString());
        }
        String jsonString = JSON.toJSONString(list);
        boolean update = lifeInfoService.update(new UpdateWrapper<LifeInfo>().eq("ID", infoId).set("LIKE_LIST", jsonString));
        return update ? JsonResult.success() : JsonResult.fail("likeLifeInfo error");
    }


}

